package com.example.rxtxdemo.rxtx2;

import cn.hutool.core.thread.ThreadUtil;
import com.fazecast.jSerialComm.SerialPort;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class SerialPortManager {


    //查找所有可用端口
    public static List<String> findPorts() {
        // 获得当前所有可用串口
        SerialPort[] serialPorts = SerialPort.getCommPorts();
        List<String> portNameList = new ArrayList<String>();
        // 将可用串口名添加到List并返回该List
        for (SerialPort serialPort : serialPorts) {
            portNameList.add(serialPort.getSystemPortName());
        }
        //去重
        portNameList = portNameList.stream().distinct().collect(Collectors.toList());
        return portNameList;
    }

    private SerialPort mSerialPort;

    public SerialPortManager() {
        mSerialPort = null;
    }

    public void init(String portName) {
        mSerialPort = SerialPort.getCommPort(portName);
        mSerialPort.openPort();
        mSerialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        mSerialPort.setComPortParameters(38400, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        mSerialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);
    }

    public void close() {
        if (mSerialPort != null && mSerialPort.isOpen()) {
            mSerialPort.closePort();
        }
    }

    /**
     * 往串口发送数据
     *
     * @param content    待发送数据
     */
    private void sendToPort(byte[] content) {
        if (!mSerialPort.isOpen()) {
            return;
        }
        mSerialPort.writeBytes(content, content.length);
    }


    public static byte[] readFromPort(SerialPort serialPort) {
        byte[] reslutData = null;
        try {
            if (!serialPort.isOpen()) {
                return null;
            };
            int i = 0;
            while (serialPort.bytesAvailable() > 0 && i++ < 5) Thread.sleep(20);
            byte[] readBuffer = new byte[serialPort.bytesAvailable()];
            int numRead = serialPort.readBytes(readBuffer, readBuffer.length);
            if (numRead > 0) {
                reslutData = readBuffer;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return reslutData;
    }

    public byte[] readWriteTest(String portName, byte[] content, long wait) {
        init(portName);
        sendToPort(content);
        ThreadUtil.sleep(wait);
        byte[] bytes = readFromPort(mSerialPort);
        close();
        return bytes;
    }


    private int write(byte[] data) {
        if (mSerialPort == null || !mSerialPort.isOpen()) {
            return 0;
        }
        return mSerialPort.writeBytes(data, data.length);
    }

}